package com.ukefu.webim.web.handler.apps.xiaoe;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder.Operator;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ukefu.core.UKDataContext;
import com.ukefu.util.Menu;
import com.ukefu.util.UKTools;
import com.ukefu.util.ai.AiUtils;
import com.ukefu.util.es.SearchDataBean;
import com.ukefu.util.es.SearchTools;
import com.ukefu.util.extra.DataExchangeInterface;
import com.ukefu.util.task.DSData;
import com.ukefu.util.task.DSDataEvent;
import com.ukefu.util.task.ExcelImportProecess;
import com.ukefu.util.task.export.ExcelExporterProcess;
import com.ukefu.util.task.process.TopicProcess;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.service.es.TopicRepository;
import com.ukefu.webim.service.repository.AiConfigRepository;
import com.ukefu.webim.service.repository.AreaTypeRepository;
import com.ukefu.webim.service.repository.ChatMessageRepository;
import com.ukefu.webim.service.repository.KnowledgeTypeRepository;
import com.ukefu.webim.service.repository.MetadataRepository;
import com.ukefu.webim.service.repository.ReporterRepository;
import com.ukefu.webim.service.repository.SMSTemplateRepository;
import com.ukefu.webim.service.repository.SceneItemRepository;
import com.ukefu.webim.service.repository.SceneRepository;
import com.ukefu.webim.service.repository.SceneTypeRepository;
import com.ukefu.webim.service.repository.ServiceAiRepository;
import com.ukefu.webim.service.repository.SysDicRepository;
import com.ukefu.webim.service.repository.TemplateRepository;
import com.ukefu.webim.service.repository.TopicItemRepository;
import com.ukefu.webim.util.OnlineUserUtils;
import com.ukefu.webim.util.impl.AiMRoundsProcesserImpl;
import com.ukefu.webim.util.impl.AiMessageAskProcesserImpl;
import com.ukefu.webim.util.server.message.ChatMessage;
import com.ukefu.webim.util.server.message.OtherMessageItem;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.AiConfig;
import com.ukefu.webim.web.model.AiMessageMapping;
import com.ukefu.webim.web.model.AiUser;
import com.ukefu.webim.web.model.KnowledgeType;
import com.ukefu.webim.web.model.MetadataTable;
import com.ukefu.webim.web.model.Scene;
import com.ukefu.webim.web.model.SceneItem;
import com.ukefu.webim.web.model.SceneType;
import com.ukefu.webim.web.model.ServiceAi;
import com.ukefu.webim.web.model.SysDic;
import com.ukefu.webim.web.model.Topic;
import com.ukefu.webim.web.model.TopicItem;
import com.ukefu.webim.web.model.UKeFuDic;

@Controller
@RequestMapping("/apps/xiaoe")
public class XiaoEController extends Handler{
	
	@Value("${web.upload-path}")
    private String path;
	
	@Value("${uk.im.server.port}")  
    private Integer port; 
	
	@Autowired
	private KnowledgeTypeRepository knowledgeTypeRes ;
	
	@Autowired
	private AreaTypeRepository areaRepository;
	
	@Autowired
	private SysDicRepository sysDicRepository;
	
	@Autowired
	private SceneTypeRepository sceneTypeRes ;
	
	@Autowired
	private SceneRepository sceneRes ;
	
	@Autowired
	private TemplateRepository templateRes ;
	
	@Autowired
	private SceneItemRepository sceneItemRes ;
	
	@Autowired
	private TopicRepository topicRes ;
	
	@Autowired
	private AiConfigRepository aiConfigRes ; 

	@Autowired
	private ChatMessageRepository chatMessageRes;
	
	@Autowired
	private MetadataRepository metadataRes ;
	
	@Autowired
	private TopicItemRepository topicItemRes ;
	
	@Autowired
	private ReporterRepository reporterRes ;
	
	@Autowired
	private ServiceAiRepository serviceAiRes ;
	
	@Autowired
	private SMSTemplateRepository smsTempletRes ;	//查询模板

	private ObjectMapper objectMapper = new ObjectMapper();
	
	@Autowired
	private AiMessageAskProcesserImpl aiMessageAskProcesserImpl ;
	
	@Autowired
	private AiMRoundsProcesserImpl aiMroundsProcesser ;
	
	@RequestMapping("/index")
    @Menu(type = "xiaoe" , subtype = "xiaoe")
    public ModelAndView list(ModelMap map , HttpServletRequest request) throws IOException {
    	map.put("serviceAiList", serviceAiRes.findByOrgi(super.getOrgi(request), new PageRequest(super.getP(request), super.getPs(request), Sort.Direction.DESC, new String[] { "createtime" }))) ;
    	return request(super.createAppsTempletResponse("/apps/business/xiaoe/serviceai/index"));
    }
	
	@RequestMapping("/serviceai/add")
    @Menu(type = "xiaoe" , subtype = "serviceai")
    public ModelAndView serviceai(ModelMap map , HttpServletRequest request ) {
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/serviceai/add"));
    }
	
	@RequestMapping("/serviceai/save")
    @Menu(type = "xiaoe" , subtype = "serviceai")
    public ModelAndView serviceaisave(ModelMap map , HttpServletRequest request ,@Valid ServiceAi ai) {
    	if(ai!=null && !StringUtils.isBlank(ai.getName())){
    		ai.setOrgi(super.getOrgi(request));
    		ai.setCreater(super.getUser(request).getId());
    		ai.setCreatetime(new Date());
    		serviceAiRes.save(ai) ;
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/index.html"));
    }
	
	@RequestMapping("/serviceai/edit")
    @Menu(type = "xiaoe" , subtype = "serviceai")
    public ModelAndView serviceaiedit(ModelMap map , HttpServletRequest request ,@Valid String id) {
		map.put("ai" , serviceAiRes.findByIdAndOrgi(id, super.getOrgi(request)) );
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/serviceai/edit"));
    }
	
	@RequestMapping("/serviceai/update")
    @Menu(type = "xiaoe" , subtype = "serviceai")
    public ModelAndView serviceaiupdate(ModelMap map , HttpServletRequest request ,@Valid ServiceAi ai) {
    	if(ai!=null && !StringUtils.isBlank(ai.getName()) && !StringUtils.isBlank(ai.getId())){
    		ServiceAi serviceAi = serviceAiRes.findByIdAndOrgi(ai.getId(), super.getOrgi(request)) ;
    		serviceAi.setName(ai.getName());
    		serviceAi.setCode(serviceAi.getId());
    		serviceAi.setDescription(ai.getDescription());
    		serviceAiRes.save(ai) ;
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/index.html"));
    }
	
	@RequestMapping("/serviceai/delete")
    @Menu(type = "xiaoe" , subtype = "serviceai")
    public ModelAndView delete(ModelMap map , HttpServletRequest request ,@Valid ServiceAi ai) {
    	if(ai!=null && !StringUtils.isBlank(ai.getId())){
    		serviceAiRes.delete(ai) ;
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/index.html"));
    }
	
    @RequestMapping("/config")
    @Menu(type = "xiaoe" , subtype = "xiaoe")
    public ModelAndView index(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String id) throws IOException {
    	if(!StringUtils.isBlank(id)) {
	    	map.put("serviceAi", serviceAiRes.findByIdAndOrgi(id, super.getOrgi(request))) ;
	    	map.put("aiConfig", AiUtils.initAiConfig(id , super.getOrgi(request))) ;
	    	map.put("skillList", OnlineUserUtils.organ(super.getOrgi(request), true))  ;
	    	
	    	
	    	List<SysDic> smsDicList = UKeFuDic.getInstance().getDic("com.dic.sms.templetype") ;
			SysDic smsDic = null;
			for(SysDic sysDic : smsDicList) {
				if(sysDic.getCode().equals("xiaoe")) {
					smsDic = sysDic ; break ;
				}
			}
			if(smsDic!=null) {
				map.addAttribute("smsTempletList",smsTempletRes.findByTemplettypeAndOrgi(smsDic.getId(), super.getOrgi(request)));
			}
	    	
	    	List<SysDic> dicList = UKeFuDic.getInstance().getDic(UKDataContext.UKEFU_SYSTEM_DIC) ;
	    	SysDic inputDic = null , outputDic = null ;
	    	for(SysDic dic : dicList){
	    		if(dic.getCode().equals(UKDataContext.UKEFU_SYSTEM_AI_INPUT)){
	    			inputDic = dic ;
	    		}
	    		if(dic.getCode().equals(UKDataContext.UKEFU_SYSTEM_AI_OUTPUT)){
	    			outputDic = dic ;
	    		}
	    	}
	    	//NOTE 已区分租户
	    	if(inputDic!=null){
	    		map.addAttribute("innputtemlet", templateRes.findByTemplettypeAndOrgi(inputDic.getId(), super.getOrgi(request))) ;
	    	}
	    	if(outputDic!=null){
	    		map.addAttribute("outputtemlet", templateRes.findByTemplettypeAndOrgi(outputDic.getId(), super.getOrgi(request))) ;
	    	}
    	}
    	return request(super.createAppsTempletResponse("/apps/business/xiaoe/index"));
    }
    
    @RequestMapping("history")
    @Menu(type = "xiaoe" , subtype = "history")
    public ModelAndView history(final ModelMap map ,final HttpServletRequest request , @Valid final String q  , @Valid final String tagget, @Valid final String matchnum) throws IOException {
//    	map.put("historyList", chatMessageRes.findByChatypeAndOrgi(UKDataContext.AiItemType.USERINPUT.toString(), super.getOrgi(request) , new PageRequest(super.getP(request), super.getPs(request) , Sort.Direction.DESC, "createtime"))) ;
//    	map.put("historyList", chatMessageRes.findByChatypeAndTousernameAndOrgi(UKDataContext.AiItemType.USERINPUT.toString(),UKDataContext.ChannelTypeEnum.AI.toString(), super.getOrgi(request) , new PageRequest(super.getP(request), super.getPs(request) , Sort.Direction.DESC, "createtime"))) ;
    	ModelAndView view = request(super.createAppsTempletResponse("/apps/business/xiaoe/chat/history")) ;
    	final String orgi = super.getOrgi(request);
    	Page<ChatMessage> page = chatMessageRes.findAll(new Specification<ChatMessage>() {
			@Override
			public Predicate toPredicate(Root<ChatMessage> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();  
				
				list.add(cb.equal(root.get("orgi").as(String.class), orgi));
				list.add(cb.equal(root.get("chatype").as(String.class), UKDataContext.AiItemType.USERINPUT.toString()));
				list.add(cb.equal(root.get("tousername").as(String.class), UKDataContext.ChannelTypeEnum.AI.toString()));
				if(!StringUtils.isBlank(q)) {
					list.add(cb.like(root.get("message").as(String.class), "%"+q+"%"));
				}
				if (!StringUtils.isBlank(tagget)) {
					if ("all".equals(tagget)) {
						list.add(cb.notEqual(root.get("tagget").as(int.class), 0));
					}else {
						list.add(cb.equal(root.get("tagget").as(int.class), Integer.parseInt(tagget)));
					}
					map.put("tagget",tagget);
				}
				if(!StringUtils.isBlank(request.getParameter("correct"))) {
					list.add(cb.equal(root.get("correct").as(int.class), request.getParameter("correct")));
					map.put("correct",request.getParameter("correct"));
				}
				if (!StringUtils.isBlank(matchnum) && "0".equals(matchnum)) {
					list.add(cb.equal(root.get("matchnum").as(int.class), 0));
					map.put("matchnum",request.getParameter("matchnum"));
				}
				Predicate[] p = new Predicate[list.size()];  
				return cb.and(list.toArray(p));   
			}
		}, new PageRequest(super.getP(request), super.getPs(request), Sort.Direction.DESC,new String[] {"createtime"}));
    	map.put("historyList",page);
    	map.put("p",super.getP(request)+1);
    	return view;
    }
    
    @RequestMapping("/history/tagget")
    @Menu(type = "xiaoe" , subtype = "history")
    public ModelAndView historymark(ModelMap map , HttpServletRequest request , @Valid String id, @Valid int tagge, @Valid String tagget, @Valid String correct, @Valid String check, @Valid String matchnum) throws IOException {
    	if (!StringUtils.isBlank(id)) {
			ChatMessage chatMessage = chatMessageRes.findById(id);
			if (chatMessage != null) {
				chatMessage.setTagget(tagge);
				chatMessageRes.save(chatMessage) ;
			}
		}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/history.html?p="+request.getParameter("p")+
    			(!StringUtils.isBlank(tagget)?"&tagget="+tagget:"")+
    			(!StringUtils.isBlank(correct)?"&correct="+correct:"")+
    			(!StringUtils.isBlank(check)?"&check="+check:"")+
    			(!StringUtils.isBlank(matchnum)?"&tagget="+matchnum:"")));
    }
    
    @RequestMapping("/history/check")
    @Menu(type = "xiaoe" , subtype = "history")
    public ModelAndView historycheck(ModelMap map , HttpServletRequest request , @Valid String id, @Valid String tagget, @Valid String correct, @Valid String check, @Valid String matchnum) throws IOException {
    	ModelAndView view = request(super.createAppsTempletResponse("/apps/business/xiaoe/chat/check"));
    	final String orgi = super.getOrgi(request) ;
    	List<ChatMessage> chatMessageList = new ArrayList<ChatMessage>();
    	if (!StringUtils.isBlank(id)) {
    		ChatMessage chatMessage = chatMessageRes.findById(id) ;
    		if (chatMessage != null) {
    			chatMessageList.add(chatMessage) ;
			}
		}else if (!StringUtils.isBlank(tagget)) {
			if ("all".equals(tagget)) {//所有标记
				chatMessageList = chatMessageRes.findByTaggetNotAndOrgi(0, orgi) ;
			}else if ("1".equals(tagget)) {//标记正确
				chatMessageList = chatMessageRes.findByTaggetAndOrgi(1, orgi) ;
			}else if ("2".equals(tagget)) {//标记错误
				chatMessageList = chatMessageRes.findByTaggetAndOrgi(2, orgi) ;
			}
		}else if (!StringUtils.isBlank(correct) && "1".equals(correct)) {//匹配正确
			chatMessageList = chatMessageRes.findByCorrectAndOrgi(true, orgi) ;
		}else if (!StringUtils.isBlank(matchnum) && "0".equals(matchnum)) {//无匹配问题列表
			chatMessageList = chatMessageRes.findByMatchnumAndOrgi(0, orgi) ;
		}
    	if (chatMessageList != null && chatMessageList.size()>0) {
    		AiUser aiUser = new AiUser("aiuser", "aiuser", System.currentTimeMillis(), orgi, null , null) ;
    		if (aiUser != null) {
    			for(ChatMessage chatMessage : chatMessageList) {
    				aiMessageAskProcesserImpl.process(chatMessage, aiMroundsProcesser, aiUser) ;
    			}
			}
		}
    	if (!StringUtils.isBlank(id)) {
    		final String idString = id;
    		map.put("historyList",chatMessageRes.findAll(new Specification<ChatMessage>() {
    			@Override
    			public Predicate toPredicate(Root<ChatMessage> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    				List<Predicate> list = new ArrayList<Predicate>();  
    				list.add(cb.like(root.get("orgi").as(String.class), orgi));
    				if(!StringUtils.isBlank(idString)) {
    					list.add(cb.like(root.get("id").as(String.class), idString));
    				}
    				Predicate[] p = new Predicate[list.size()];  
    				return cb.and(list.toArray(p));   
    			}
    		}, new PageRequest(super.getP(request), super.getPs(request), Sort.Direction.DESC,new String[] {"createtime"})));
		}else {
			view = this.history(map,request,null,tagget,matchnum);
		}
    	return view ;
    }
    
    @RequestMapping("/config/save")
    @Menu(type = "setting" , subtype = "aiconfig" )
    public ModelAndView aiconfig(ModelMap map , HttpServletRequest request , @Valid AiConfig aiConfig, @Valid String[] hotmsg, @Valid String[] topicid, @Valid String[] keywords , @Valid String[] skill) throws JsonProcessingException {
    	List<AiConfig> tempAiConfigList = aiConfigRes.findByOrgiAndAiid(super.getOrgi(request) , aiConfig.getAiid()) ;
    	AiConfig tempAiConfig = null ;
    	if(tempAiConfigList.size() > 0){
    		tempAiConfig = tempAiConfigList.get(0) ;
    	}
    	if(tempAiConfig == null){
    		tempAiConfig = aiConfig;
    		aiConfig.setCreater(super.getUser(request).getId());
    	}else{
    		aiConfig.setId(tempAiConfig.getId());
    		aiConfig.setCreater(super.getUser(request).getId());
    		aiConfig.setCreatetime(tempAiConfig.getCreatetime());
    		aiConfig.setOrgi(super.getOrgi(request));
    		tempAiConfig = aiConfig ;
    	}
    	tempAiConfig.setOrgi(super.getOrgi(request));
    	
    	if(hotmsg != null && hotmsg.length > 0){
    		List<OtherMessageItem> otherMessageList = new ArrayList<OtherMessageItem>();
    		for(int i=0 ; i < hotmsg.length ; i ++){
    			OtherMessageItem otherMessageItem = new OtherMessageItem();
    			otherMessageItem.setTitle(hotmsg[i]);
    			if(topicid!=null && topicid.length == hotmsg.length) {
    				otherMessageItem.setId(topicid[i]);
    			}
    			otherMessageList.add(otherMessageItem) ;
    		}
    		tempAiConfig.setHotmsg(objectMapper.writeValueAsString(otherMessageList)) ;
    	}else{
    		tempAiConfig.setHotmsg(null) ;
    	}
    	List<AiMessageMapping> mappingList = new ArrayList<AiMessageMapping>();
    	if(keywords!=null && keywords.length > 0 && skill!=null && skill.length == keywords.length) {
    		for(int i= 0 ; i<keywords.length ; i++) {
    			mappingList.add(new AiMessageMapping(keywords[i] , skill[i])) ;
    		}
    		
    	}
    	if(mappingList.size() > 0){
    		tempAiConfig.setBussmapping(objectMapper.writeValueAsString(mappingList));
    	}else {
    		tempAiConfig.setBussmapping(null);
    	}
    	aiConfigRes.save(tempAiConfig) ;
    	
    	CacheHelper.getSystemCacheBean().put(UKDataContext.SYSTEM_CACHE_AI_CONFIG+"_"+tempAiConfig.getAiid(),tempAiConfig, super.getOrgi(request)) ;
    	
    	map.put("aiConfig", tempAiConfig) ;
        return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/index.html"));
    }
    
    @RequestMapping("/chat")
    @Menu(type = "xiaoe" , subtype = "chat")
    public ModelAndView chat(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String type, @Valid String aiid) {
    	List<ServiceAi> serviceAiList = serviceAiRes.findByOrgi(super.getOrgi(request)) ; 
    	map.put("serviceAiList",serviceAiList ) ;
    	if(serviceAiList.size() > 0) {
    		ServiceAi serviceAi = serviceAiList.get(0) ;
    		if(!StringUtils.isBlank(aiid)) {
	    		for(ServiceAi ai : serviceAiList) {
	    			if(ai.getId().equals(aiid)) {
	    				serviceAi = ai ;
	    			}
	    		}
    		}
    		map.put("serviceAi",serviceAi) ;
    		map.put("aiid",serviceAi.getId()) ;
    		
	    	map.put("import", port) ;
	    	map.put("appid", super.getOrgi(request)) ;
	    	map.put("userid", super.getUser(request).getId()) ;
	    	map.put("schema", request.getScheme()) ;
	    	map.put("sessionid", super.getUser(request).getSessionid()) ;
	    	map.addAttribute("aiConfig", UKTools.initAiConfig(serviceAi.getId(), super.getOrgi(request)));
//	    	map.put("topicList",topicRes.getTopicByTopAndOrgiAndAiid(true,super.getOrgi(request) , serviceAi.getId(), super.getP(request),  super.getPs(request))) ;
    	}
    	
    	
    	return request(super.createAppsTempletResponse("/apps/business/xiaoe/chat/index"));
    }
    @RequestMapping("/chat/toptopic")
    @Menu(type = "xiaoe" , subtype = "chat")
    public ModelAndView getTopTopic(ModelMap map , HttpServletRequest request , @Valid String aiid) {
    	map.put("topicList",topicRes.getTopicByTopAndOrgi(true,super.getOrgi(request) , aiid, super.getP(request),  super.getPs(request))) ;
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/chat/topic"));
    }
    
    
    
    @RequestMapping("/knowledge")
    @Menu(type = "xiaoe" , subtype = "knowledge")
    public ModelAndView knowledge(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String type, @Valid String aiid) {
    	List<ServiceAi> serviceAiList = serviceAiRes.findByOrgi(super.getOrgi(request)) ; 
    	map.put("serviceAiList",serviceAiList ) ;
    	if(serviceAiList.size() > 0) {
    		ServiceAi serviceAi = serviceAiList.get(0) ;
    		if(!StringUtils.isBlank(aiid)) {
	    		for(ServiceAi ai : serviceAiList) {
	    			if(ai.getId().equals(aiid)) {
	    				serviceAi = ai ;
	    			}
	    		}
    		}
    		map.put("serviceAi",serviceAi) ;
    		map.put("aiid",aiid = serviceAi.getId()) ;
    		
    		List<KnowledgeType> knowledgeTypeList = knowledgeTypeRes.findByOrgiAndTypeidOrderBySortindexAsc(super.getOrgi(request) , serviceAi.getId())  ; 
        	map.put("knowledgeTypeList", knowledgeTypeList);
        	KnowledgeType ktype = null ;
        	if(!StringUtils.isBlank(type)){
        		for(KnowledgeType knowledgeType : knowledgeTypeList){
        			if(knowledgeType.getId().equals(type)){
        				ktype = knowledgeType ;
        				break ;
        			}
        		}
        	}
        	if(ktype!=null){
        		map.put("curtype", ktype) ;
        		map.put("topicList", topicRes.getTopicByCateAndOrgi(ktype.getId(),super.getOrgi(request), q, super.getP(request), super.getPs(request)))  ;
        	}else{
        		map.put("topicList", topicRes.getTopicByAiidAndOrgi(aiid,super.getOrgi(request), q, super.getP(request), super.getPs(request)))  ;
        	}
    	}
    	
    	if(!StringUtils.isBlank(q)){
    		map.put("q", q) ;
     	}
    	map.addAttribute("areaList", areaRepository.findByOrgi(super.getOrgi(request))) ;
    	return request(super.createAppsTempletResponse("/apps/business/xiaoe/knowledge/index"));
    }
    
    @RequestMapping("/knowledge/add")
    @Menu(type = "xiaoe" , subtype = "knowledgeadd")
    public ModelAndView knowledgeadd(ModelMap map , HttpServletRequest request , @Valid String type, @Valid String aiid) throws JsonParseException, JsonMappingException, IOException {
    	map.put("type", type);
    	map.put("aiid", aiid);
    	
    	BoolQueryBuilder booleanQueryBuilder = new BoolQueryBuilder();
    	booleanQueryBuilder.must(termQuery("orgi" , super.getOrgi(request))) ;
		if(!StringUtils.isBlank(type)){
			booleanQueryBuilder.must(termQuery("cate" , type)) ;
		}
		if(!StringUtils.isBlank(aiid)){
			booleanQueryBuilder.must(termQuery("aiid" , aiid)) ;
		}
    	Page<Topic> topicList = this.topicRes.getTopicByCon(booleanQueryBuilder, super.getP(request), super.getPs(request));
    	map.addAttribute("topicList", topicList);
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/knowledge/add"));
    }
    
    @RequestMapping("/knowledge/topicre")
    @Menu(type = "xiaoe" , subtype = "knowledgeadd")
    public ModelAndView knowledgeRe(ModelMap map , HttpServletRequest request , @Valid String type, @Valid String aiid ,@Valid String id) throws JsonParseException, JsonMappingException, IOException {
    	map.put("type", type);
    	map.put("aiid", aiid);
    	map.put("id", id);
    	
    	Topic top = this.topicRes.findByIdAndOrgi(id,super.getOrgi(request));
    	if(!StringUtils.isBlank(top.getRelevance())) {
	    	List<OtherMessageItem> topicRelevanceList = OnlineUserUtils.objectMapper.readValue(top.getRelevance(), UKTools.getCollectionType(ArrayList.class, OtherMessageItem.class))  ;
			map.addAttribute("topicsList", topicRelevanceList);
    	}
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/knowledge/topicre"));
    }
    
    @RequestMapping("/knowledge/topicre/delete")
    @Menu(type = "xiaoe" , subtype = "knowledgeadd")
    public ModelAndView delKnowledgeRe(ModelMap map , HttpServletRequest request , @Valid String type, @Valid String aiid, @Valid String topicsid , @Valid String id) throws JsonParseException, JsonMappingException, IOException {
    	map.put("type", type);
    	map.put("aiid", aiid);
    	map.put("id", id);
    	Topic top = this.topicRes.findByIdAndOrgi(id,super.getOrgi(request));
    	
    	if(top != null) {
    		List<OtherMessageItem> otherMessageItemList = OnlineUserUtils.objectMapper.readValue(top.getRelevance(), UKTools.getCollectionType(ArrayList.class, OtherMessageItem.class))  ;
			if(!otherMessageItemList.isEmpty()) {
				for(int i = 0; i < otherMessageItemList.size() ;i++) {
					if(otherMessageItemList.get(i).getId().equals(topicsid)) {
						otherMessageItemList.remove(otherMessageItemList.get(i));
					}
				}
			}
			if(!otherMessageItemList.isEmpty()) {
				top.setRelevance(UKTools.toJson(otherMessageItemList));
			}else {
				top.setRelevance(null);
			}
			this.topicRes.save(top);
    	}
    	
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/knowledge/topicre.html?aiid="+aiid+"&id="+id+(!StringUtils.isBlank(type) ? "&type="+type : "")));
    }
    
    @RequestMapping("/knowledge/topiclist")
    @Menu(type = "xiaoe" , subtype = "knowledgeadd")
    public ModelAndView knowledgeTopicList(ModelMap map , HttpServletRequest request , @Valid String type, @Valid String aiid ,@Valid String id) throws JsonParseException, JsonMappingException, IOException {
    	map.put("type", type);
    	map.put("aiid", aiid);
    	map.put("id", id);
    	
    	BoolQueryBuilder booleanQueryBuilder = new BoolQueryBuilder();
    	booleanQueryBuilder.must(termQuery("orgi" , super.getOrgi(request))) ;
    	if(!StringUtils.isBlank(aiid)){
    		//只查询该机器人下的知识
    		booleanQueryBuilder.must(termQuery("aiid" , aiid)) ;
    	}
    	
    	Topic top = this.topicRes.findByIdAndOrgi(id,super.getOrgi(request));
    	if(!StringUtils.isBlank(top.getRelevance())) {
    		//屏蔽已关联的知识
    		List<OtherMessageItem> topicRelevanceList = OnlineUserUtils.objectMapper.readValue(top.getRelevance(), UKTools.getCollectionType(ArrayList.class, OtherMessageItem.class))  ;
    		if(!topicRelevanceList.isEmpty()) {
    			BoolQueryBuilder bool = new BoolQueryBuilder();
    			for(int i = 0; i < topicRelevanceList.size() ;i++) {
    				bool.should(termQuery("id" , topicRelevanceList.get(i).getId()));
    			}
    			booleanQueryBuilder.mustNot(bool) ;
    		}
    	}
    	if(!StringUtils.isBlank(request.getParameter("q"))){
   		 map.addAttribute("q", request.getParameter("q"));
   		 // 只查询，标题，类似问题，内容
   		 booleanQueryBuilder.must(new QueryStringQueryBuilder(request.getParameter("q")).field("title").field("content").field("silimar").defaultOperator(Operator.AND)) ;
	    }
    	//屏蔽自己
    	booleanQueryBuilder.mustNot(termQuery("id" , id)) ;
    	Page<Topic> topicList = this.topicRes.getTopicByCon(booleanQueryBuilder, super.getP(request), super.getPs(request));
    	map.addAttribute("topicsList", topicList);
    	
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/knowledge/topiclist"));
    }
    
    @RequestMapping("/knowledge/topiclist/save")
    @Menu(type = "xiaoe" , subtype = "knowledgeadd")
    public ModelAndView knowledgeTopicListSave(ModelMap map , HttpServletRequest request , @Valid String type, @Valid String aiid, @Valid String ids[] , @Valid String id) throws JsonParseException, JsonMappingException, IOException {
    	map.put("type", type);
    	map.put("aiid", aiid);
    	Topic top = this.topicRes.findByIdAndOrgi(id,super.getOrgi(request));
    	
    	if(top != null) {
    		List<OtherMessageItem> otherMessageItemList = new ArrayList<OtherMessageItem>();
    		if(!StringUtils.isBlank(top.getRelevance())) {
    			//查出原先已关联的知识
    			List<OtherMessageItem> topicRelList = OnlineUserUtils.objectMapper.readValue(top.getRelevance(), UKTools.getCollectionType(ArrayList.class, OtherMessageItem.class))  ;
    			for(OtherMessageItem topic : topicRelList) {
    				otherMessageItemList.add(topic);
    			}
    		}
    		if(ids != null && ids.length > 0) {
    			Iterable<Topic> topicList = this.topicRes.findByIdInAndOrgi(Arrays.asList(ids),super.getOrgi(request));
    			OtherMessageItem otherMessageItem = null;
    			for(Topic topic :topicList) {
    				otherMessageItem = new OtherMessageItem();
    				otherMessageItem.setId(topic.getId());
    				otherMessageItem.setTitle(topic.getTitle());
    				otherMessageItemList.add(otherMessageItem);
    			}
    		}
    		if(!otherMessageItemList.isEmpty()) {
				top.setRelevance(UKTools.toJson(otherMessageItemList));
			}else {
    			top.setRelevance(null);
    		}
    		this.topicRes.save(top);
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/knowledge/topicre.html?aiid="+aiid+"&id="+id+(!StringUtils.isBlank(type) ? "&type="+type : "")));
    }
    
    @RequestMapping("/knowledge/save")
    @Menu(type = "xiaoe" , subtype = "knowledgesave")
    public ModelAndView knowledgesave(HttpServletRequest request ,@Valid Topic topic , @Valid String type, @Valid String aiid , @Valid String relevance[] ) {
    	if(!StringUtils.isBlank(topic.getTitle())){
    		if(!StringUtils.isBlank(type)){
    			topic.setCate(type);
    		}else{
    			topic.setCate(UKDataContext.DEFAULT_TYPE);
    		}
    		topic.setOrgi(super.getOrgi(request));
    		topic.setAiid(aiid);
    		
    		topicRes.save(topic) ;
    		List<TopicItem> topicItemList = new ArrayList<TopicItem>();
    		for(String item : topic.getSilimar()) {
				TopicItem topicItem = new TopicItem();
				topicItem.setTitle(item);
				topicItem.setTopicid(topic.getId());
				topicItem.setOrgi(topic.getOrgi());
				topicItem.setCreater(topic.getCreater());
				topicItem.setCreatetime(new Date());
				topicItemList.add(topicItem) ;
			}
			if(topicItemList.size() > 0) {
				topicItemRes.save(topicItemList) ;
			}
    		/**
    		 * 重新缓存
    		 * 
    		 */
    		OnlineUserUtils.resetHotTopic((DataExchangeInterface) UKDataContext.getContext().getBean("topic") , super.getUser(request) , super.getOrgi(request) , aiid) ;
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/knowledge.html?aiid="+aiid+(!StringUtils.isBlank(type) ? "&type="+type : "")));
    }
    
    @RequestMapping("/knowledge/edit")
    @Menu(type = "xiaoe" , subtype = "knowledgeedit")
    public ModelAndView knowledgeedit(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String debug , @Valid String type, @Valid String aiid) throws JsonParseException, JsonMappingException, IOException {
    	map.put("type", type);
    	map.put("aiid", aiid);
    	if(!StringUtils.isBlank(id)){
    		Topic topic = topicRes.findByIdAndOrgi(id,super.getOrgi(request));
    		map.put("topic", topic) ;
    		
    	}
    	if(!StringUtils.isBlank(debug)) {
    		map.put("debug", true) ;
    	}
    	List<KnowledgeType> knowledgeTypeList = knowledgeTypeRes.findByOrgiAndTypeidOrderBySortindexAsc(super.getOrgi(request),aiid)  ; 
    	map.put("knowledgeTypeList", knowledgeTypeList);
    	
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/knowledge/edit"));
    }
    
    @RequestMapping("/knowledge/update")
    @Menu(type = "xiaoe" , subtype = "knowledgeupdate")
    public ModelAndView knowledgeupdate(HttpServletRequest request ,@Valid Topic topic , @Valid String type , @Valid String debug, @Valid String aiid, @Valid String relevance[]) {
    	ModelAndView view = request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/knowledge.html?aiid="+aiid+(!StringUtils.isBlank(type) ? "&type="+type : ""))) ;
    	Topic temp = topicRes.findByIdAndOrgi(topic.getId(),super.getOrgi(request)) ;
    	if(!StringUtils.isBlank(debug)) {
    		view = request(super.createRequestPageTempletResponse("/public/success")) ;
    	}
    	if(!StringUtils.isBlank(topic.getTitle())){
    		
    		if(!StringUtils.isBlank(type)){
    			topic.setCate(type);
    		}else{
    			topic.setCate(UKDataContext.DEFAULT_TYPE);
    		}
    		topic.setCreater(temp.getCreater());
    		topic.setCreatetime(temp.getCreatetime());
    		topic.setOrgi(super.getOrgi(request));
    		topic.setAiid(aiid);
    		topic.setRelevance(temp.getRelevance());
    		
    		topicRes.save(topic) ;
    		topicItemRes.delete(topicItemRes.findByTopicidAndOrgi(topic.getId(),super.getOrgi(request))) ;
    		List<TopicItem> topicItemList = new ArrayList<TopicItem>();
    		for(String item : topic.getSilimar()) {
				TopicItem topicItem = new TopicItem();
				topicItem.setTitle(item);
				topicItem.setTopicid(topic.getId());
				topicItem.setOrgi(topic.getOrgi());
				topicItem.setCreater(topic.getCreater());
				topicItem.setCreatetime(new Date());
				topicItemList.add(topicItem) ;
			}
			if(topicItemList.size() > 0) {
				topicItemRes.save(topicItemList) ;
			}
    		
    		/**
    		 * 重新缓存
    		 * 
    		 */
    		OnlineUserUtils.resetHotTopic((DataExchangeInterface) UKDataContext.getContext().getBean("topic") , super.getUser(request) , super.getOrgi(request), aiid) ;
    	}
    	return view;
    }
    
    @RequestMapping("/knowledge/delete")
    @Menu(type = "xiaoe" , subtype = "knowledgedelete")
    public ModelAndView knowledgedelete(HttpServletRequest request ,@Valid String id , @Valid String type, @Valid String aiid) {
    	if(!StringUtils.isBlank(id)){
    		topicRes.delete(topicRes.findByIdAndOrgi(id,super.getOrgi(request)));
    		/**
    		 * 重新缓存
    		 * 
    		 */
    		topicItemRes.delete(topicItemRes.findByTopicidAndOrgi(id,super.getOrgi(request))) ;
    		
    		OnlineUserUtils.resetHotTopic((DataExchangeInterface) UKDataContext.getContext().getBean("topic") , super.getUser(request) , super.getOrgi(request), aiid) ;
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/knowledge.html?aiid="+aiid+(!StringUtils.isBlank(type) ? "&type="+type : "")));
    }
    
    @RequestMapping("/knowledge/type/add")
    @Menu(type = "xiaoe" , subtype = "knowledgetypeadd")
    public ModelAndView knowledgetypeadd(ModelMap map , HttpServletRequest request ,@Valid String type, @Valid String aiid) {
    	map.addAttribute("areaList", areaRepository.findByOrgi(super.getOrgi(request))) ;
    	map.addAttribute("aiid", aiid) ;
    	List<KnowledgeType> knowledgeTypeList = knowledgeTypeRes.findByOrgiAndTypeidOrderBySortindexAsc(super.getOrgi(request) , aiid)  ; 
    	map.put("knowledgeTypeList", knowledgeTypeList);
    	
    	if(!StringUtils.isBlank(type)){
    		map.put("type", type) ;
    	}
    	
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/knowledge/addtype"));
    }
    
    @RequestMapping("/knowledge/type/save")
    @Menu(type = "xiaoe" , subtype = "knowledgetypesave")
    public ModelAndView knowledgetypesave(HttpServletRequest request ,@Valid KnowledgeType type, @Valid String aiid) {
    	if(StringUtils.isBlank(type.getParentid())){
			type.setParentid("0");
		}
    	List<KnowledgeType> knowledgeTypeList = knowledgeTypeRes.findByNameAndOrgiAndTypeidAndParentidOrderBySortindexAsc(type.getName(), super.getOrgi(request),aiid,type.getParentid()) ;
    	if(knowledgeTypeList == null || knowledgeTypeList.size() == 0 ){
    		type.setOrgi(super.getOrgi(request));
    		type.setCreatetime(new Date());
    		type.setId(UKTools.getUUID());
    		type.setTypeid(aiid);
    		type.setUpdatetime(new Date());
    		type.setCreater(super.getUser(request).getId());
    		knowledgeTypeRes.save(type) ;
    		OnlineUserUtils.resetHotTopicType((DataExchangeInterface) UKDataContext.getContext().getBean("topictype") , super.getUser(request), super.getOrgi(request), aiid);
    	}else {
    		return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/knowledge.html?aiid="+aiid+"&msg=k_type_exist"));
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/knowledge.html?aiid="+aiid));
    }
    
    @RequestMapping("/knowledge/type/edit")
    @Menu(type = "xiaoe" , subtype = "knowledgetypeedit")
    public ModelAndView knowledgetypeedit(ModelMap map , HttpServletRequest request, @Valid String type , @Valid String aiid) {
    	map.put("knowledgeType", knowledgeTypeRes.findByIdAndOrgi(type,super.getOrgi(request))) ;
    	map.put("aiid", aiid) ;
    	map.addAttribute("areaList", areaRepository.findByOrgi(super.getOrgi(request))) ;
    	
    	List<KnowledgeType> knowledgeTypeList = knowledgeTypeRes.findByOrgiAndTypeidOrderBySortindexAsc(super.getOrgi(request) , aiid)  ; 
    	map.put("knowledgeTypeList", knowledgeTypeList);
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/knowledge/edittype"));
    }
    
    @RequestMapping("/knowledge/type/update")
    @Menu(type = "xiaoe" , subtype = "knowledgetypeupdate")
    public ModelAndView knowledgetypeupdate(HttpServletRequest request ,@Valid KnowledgeType type, @Valid String aiid) {
    	if(StringUtils.isBlank(type.getParentid())){
			type.setParentid("0");
		}else{
			type.setParentid(type.getParentid());
		}
    	KnowledgeType temp = knowledgeTypeRes.findByIdAndOrgi(type.getId(), super.getOrgi(request)) ;
    	if (temp != null) {
    		List<KnowledgeType> knowledgeTypeList = knowledgeTypeRes.findByNameAndOrgiAndTypeidAndParentidAndIdNot(type.getName(), super.getOrgi(request),aiid,temp.getParentid(),type.getId()) ;
    		if(knowledgeTypeList == null || knowledgeTypeList.size() == 0 ){
    			temp.setName(type.getName());
    			temp.setTypeid(aiid);
    			temp.setParentid(type.getParentid());
    			temp.setSortindex(type.getSortindex());
    			if(StringUtils.isBlank(type.getParentid()) || type.getParentid().equals("0")){
    				temp.setParentid("0");
    			}else{
    				temp.setParentid(type.getParentid());
    			}
    			if(!temp.getParentid().equals(temp.getId())) {
    				knowledgeTypeRes.save(temp) ;
    				OnlineUserUtils.resetHotTopicType((DataExchangeInterface) UKDataContext.getContext().getBean("topictype") , super.getUser(request), super.getOrgi(request), aiid);
    			}else {
    				return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/knowledge.html?aiid="+aiid+"&msg=k_type_parent&type="+type.getId()));
    			}
    		}else {
    			return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/knowledge.html?aiid="+aiid+"&msg=k_type_exist&type="+type.getId()));
    		}
		}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/knowledge.html?aiid="+aiid+"&type="+type.getId()));
    }
    
    @RequestMapping("/knowledge/type/delete")
    @Menu(type = "xiaoe" , subtype = "knowledgedelete")
    public ModelAndView knowledgetypedelete(HttpServletRequest request ,@Valid String id , @Valid String type, @Valid String aiid) {
    	if (!StringUtils.isBlank(id)) {
    		KnowledgeType temp = knowledgeTypeRes.findByIdAndOrgi(id, super.getOrgi(request)) ;
    		String parentid = "0";
    		if (temp != null) {
				if (!StringUtils.isBlank(temp.getParentid())) {
					parentid = temp.getParentid();
				}
				Page<Topic> page = topicRes.getTopicByCateAndOrgi(type,super.getOrgi(request), null, super.getP(request), 100000) ;
				if (page != null && page.getContent().size() > 0) {
					for(Topic topic : page.getContent()) {
						topic.setCate(parentid);
					}
					topicRes.save(page.getContent());
				}
				List<KnowledgeType> sonlist = knowledgeTypeRes.findByOrgiAndTypeidAndParentid(super.getOrgi(request), temp.getTypeid(), temp.getId());
				if (sonlist != null && sonlist.size() > 0) {
					for(KnowledgeType sontype : sonlist) {
						sontype.setParentid(parentid);
					}
					knowledgeTypeRes.save(sonlist);
				}
				knowledgeTypeRes.delete(id);
				OnlineUserUtils.resetHotTopicType((DataExchangeInterface) UKDataContext.getContext().getBean("topictype") , super.getUser(request), super.getOrgi(request), aiid);

			}
		}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/knowledge.html?aiid="+aiid));
    }
    
    @RequestMapping("/knowledge/area")
    @Menu(type = "admin" , subtype = "area")
    public ModelAndView area(ModelMap map ,HttpServletRequest request , @Valid String id, @Valid String aiid) {
    	map.put("aiid", aiid) ;
    	SysDic sysDic = sysDicRepository.findByCode(UKDataContext.UKEFU_SYSTEM_AREA_DIC) ;
    	if(sysDic!=null){
	    	map.addAttribute("sysarea", sysDic) ;
	    	map.addAttribute("areaList", sysDicRepository.findByDicidOrderBySortindexAsc(sysDic.getId())) ;
    	}
    	map.addAttribute("cacheList", UKeFuDic.getInstance().getDic(UKDataContext.UKEFU_SYSTEM_AREA_DIC)) ;
    	
    	map.put("knowledgeType", knowledgeTypeRes.findByIdAndOrgi(id,super.getOrgi(request))) ;
        return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/knowledge/area"));
    }
    
    
    @RequestMapping("/knowledge/area/update")
    @Menu(type = "admin" , subtype = "organ")
    public ModelAndView areaupdate(HttpServletRequest request ,@Valid KnowledgeType type, @Valid String aiid) {
    	KnowledgeType temp = knowledgeTypeRes.findByIdAndOrgi(type.getId(), super.getOrgi(request)) ;
    	if(temp != null){
    		temp.setArea(type.getArea());
    		knowledgeTypeRes.save(temp) ;
    		OnlineUserUtils.resetHotTopicType((DataExchangeInterface) UKDataContext.getContext().getBean("topictype") , super.getUser(request), super.getOrgi(request), aiid);
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/knowledge.html?aiid="+aiid+"&type="+type.getId()));
    }
    
    
    @RequestMapping("/knowledge/imp")
    @Menu(type = "xiaoe" , subtype = "knowledge")
    public ModelAndView imp(ModelMap map , HttpServletRequest request , @Valid String type, @Valid String aiid) {
    	map.addAttribute("type", type) ;
    	map.addAttribute("aiid", aiid) ;
        return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/knowledge/imp"));
    }
    
    @RequestMapping("/knowledge/impsave")
    @Menu(type = "xiaoe" , subtype = "knowledge")
    public ModelAndView impsave(ModelMap map , HttpServletRequest request , @RequestParam(value = "cusfile", required = false) MultipartFile cusfile , @Valid String type, @Valid String aiid) throws IOException {
    	DSDataEvent event = new DSDataEvent();
    	String fileName = "xiaoe/"+UKTools.getUUID()+cusfile.getOriginalFilename().substring(cusfile.getOriginalFilename().lastIndexOf(".")) ;
    	File excelFile = new File(path , fileName) ;
    	if(!excelFile.getParentFile().exists()){
    		excelFile.getParentFile().mkdirs() ;
    	}
    	MetadataTable table = metadataRes.findByTablenameIgnoreCase("uk_xiaoe_topic") ;
    	if(table!=null){
	    	FileUtils.writeByteArrayToFile(new File(path , fileName), cusfile.getBytes());
	    	event.setDSData(new DSData(table,excelFile , cusfile.getContentType(), super.getUser(request)));
	    	event.getDSData().setClazz(Topic.class);
	    	event.setOrgi(super.getOrgi(request));
	    	if(!StringUtils.isBlank(type)){
	    		event.getValues().put("cate", type) ;
	    	}else{
	    		event.getValues().put("cate", UKDataContext.DEFAULT_TYPE) ;
	    	}
	    	event.getValues().put("creater", super.getUser(request).getId()) ;
	    	event.getValues().put("aiid", aiid) ;
	    	event.getDSData().setProcess(new TopicProcess(topicRes));
	    	reporterRes.save(event.getDSData().getReport()) ;
	    	new ExcelImportProecess(event).process() ;		//启动导入任务
    	}
    	
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/knowledge.html?aiid="+aiid+"&type="+type));
    }
    
    @RequestMapping("/knowledge/batdelete")
    @Menu(type = "xiaoe" , subtype = "knowledge")
    public ModelAndView batdelete(ModelMap map , HttpServletRequest request , HttpServletResponse response , @Valid String[] ids ,@Valid String type, @Valid String aiid) throws IOException {
    	if(ids!=null && ids.length > 0){
    		Iterable<Topic> topicList = topicRes.findByIdInAndOrgi(Arrays.asList(ids),super.getOrgi(request)) ;
    		topicRes.delete(topicList);
    		for(Topic topic : topicList) {
    			topicItemRes.delete(topicItemRes.findByTopicidAndOrgi(topic.getId(),super.getOrgi(request))) ;
    		}
    	}
    	
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/knowledge.html?aiid="+aiid+(!StringUtils.isBlank(type) ? "&type="+type:"")));
    }
    
    @RequestMapping("/knowledge/expids")
    @Menu(type = "xiaoe" , subtype = "knowledge")
    public void expids(ModelMap map , HttpServletRequest request , HttpServletResponse response , @Valid String[] ids, @Valid String aiid) throws IOException {
    	if(ids!=null && ids.length > 0){
    		Iterable<Topic> topicList = topicRes.findByIdInAndOrgi(Arrays.asList(ids),super.getOrgi(request)) ;
    		MetadataTable table = metadataRes.findByTablenameIgnoreCase("uk_xiaoe_topic") ;
    		List<Map<String,Object>> values = new ArrayList<Map<String,Object>>();
    		for(Topic topic : topicList){
    			values.add(UKTools.transBean2Map(topic)) ;
    		}
    		
    		response.setHeader("content-disposition", "attachment;filename=UCKeFu-Contacts-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls");  
    		if(table!=null){
    			ExcelExporterProcess excelProcess = new ExcelExporterProcess( values, table, response.getOutputStream()) ;
    			excelProcess.process();
    		}
    	}
    	
        return ;
    }
    
    @RequestMapping("/knowledge/expall")
    @Menu(type = "xiaoe" , subtype = "knowledge")
    public void expall(ModelMap map , HttpServletRequest request , HttpServletResponse response,@Valid String type, @Valid String aiid) throws IOException {
    	Iterable<Topic> topicList = topicRes.getTopicByOrgi(super.getOrgi(request) ,type , null, new PageRequest(super.getP(request) , 10000)) ;
    	
    	MetadataTable table = metadataRes.findByTablenameIgnoreCase("uk_xiaoe_topic") ;
		List<Map<String,Object>> values = new ArrayList<Map<String,Object>>();
		for(Topic topic : topicList){
			values.add(UKTools.transBean2Map(topic)) ;
		}
		
		response.setHeader("content-disposition", "attachment;filename=UCKeFu-XiaoE-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls");  
		
		if(table!=null){
			ExcelExporterProcess excelProcess = new ExcelExporterProcess( values, table, response.getOutputStream()) ;
			excelProcess.process();
		}
        return ;
    }
    
    @RequestMapping("/knowledge/expsearch")
    @Menu(type = "xiaoe" , subtype = "knowledge")
    public void expall(ModelMap map , HttpServletRequest request , HttpServletResponse response , @Valid String q , @Valid String type, @Valid String aiid) throws IOException {
    	
    	Iterable<Topic> topicList = topicRes.getTopicByOrgi(super.getOrgi(request) , type , q, new PageRequest(super.getP(request) , 10000)) ;
    	
    	MetadataTable table = metadataRes.findByTablenameIgnoreCase("uk_xiaoe_topic") ;
		List<Map<String,Object>> values = new ArrayList<Map<String,Object>>();
		for(Topic topic : topicList){
			values.add(UKTools.transBean2Map(topic)) ;
		}
		
		response.setHeader("content-disposition", "attachment;filename=UCKeFu-XiaoE-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls");  
		
		if(table!=null){
			ExcelExporterProcess excelProcess = new ExcelExporterProcess( values, table, response.getOutputStream()) ;
			excelProcess.process();
		}
        return ;
    }
    
    
    
    @RequestMapping("/scene")
    @Menu(type = "xiaoe" , subtype = "scene")
    public ModelAndView scene(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String type) {
    	List<SceneType> sceneTypeList = sceneTypeRes.findByOrgi(super.getOrgi(request))  ; 
    	map.put("sceneTypeList", sceneTypeList);
    	SceneType stype = null ;
    	if(!StringUtils.isBlank(type)){
    		for(SceneType sceneType : sceneTypeList){
    			if(sceneType.getId().equals(type)){
    				stype = sceneType ;
    				break ;
    			}
    		}
    	}
    	if(!StringUtils.isBlank(q)){
    		map.put("q", q) ;
     	}
    	if(stype!=null){
    		map.put("curtype", stype) ;
    		map.put("sceneList", sceneRes.findByOrgiAndCate(super.getOrgi(request) , stype.getId(),new PageRequest(super.getP(request), super.getPs(request))))  ;
    	}else{
    		map.put("sceneList", sceneRes.findByOrgiAndCate(super.getOrgi(request) , UKDataContext.DEFAULT_TYPE,new PageRequest(super.getP(request), super.getPs(request))))  ;
    	}
    	map.addAttribute("areaList", areaRepository.findByOrgi(super.getOrgi(request))) ;
    	return request(super.createAppsTempletResponse("/apps/business/xiaoe/scene/index"));
    }
    
    @RequestMapping("/scene/add")
    @Menu(type = "xiaoe" , subtype = "sceneadd")
    public ModelAndView sceneadd(ModelMap map , HttpServletRequest request , @Valid String type) {
    	map.put("type", type);
    	map.put("inputConList", UKeFuDic.getInstance().getSysDic("com.dic.xiaoe.input"));
    	map.put("outputConList", UKeFuDic.getInstance().getSysDic("com.dic.xiaoe.output"));
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/scene/add"));
    }
    
    @RequestMapping("/scene/save")
    @Menu(type = "xiaoe" , subtype = "scenesave")
    public ModelAndView scenesave(HttpServletRequest request ,@Valid Scene scene , @Valid String[] userinput, @Valid String[] aireply , @Valid String type) throws IOException{
    	if(!StringUtils.isBlank(scene.getTitle())){
    		if(!StringUtils.isBlank(type)){
    			scene.setCate(type);
    		}else{
    			scene.setCate(UKDataContext.DEFAULT_TYPE);
    		}
    		if(userinput!=null && userinput.length >0){
    			scene.setUserinput(userinput[0]);
    		}
    		if(aireply!=null && aireply.length >0){
    			scene.setAireply(aireply[0]);
    		}
    		scene.setOrgi(super.getOrgi(request));
    		scene.setCreater(super.getUser(request).getId());
    		scene.setCreatetime(new Date());
    		
    		if(userinput!=null && userinput.length >0){
    			List<SceneItem> userInputItems = new ArrayList<SceneItem>();
    			for(int i=0 ; i<userinput.length ; i++){
    				String user = userinput[i] ;
    				if(!StringUtils.isBlank(user)){
	    				SceneItem item = new SceneItem();
	    				item.setContent(user);
	    				item.setOrgi(super.getOrgi(request));
	    				item.setCreater(super.getUser(request).getId());
	    				item.setInx(i);
	    				item.setInputcon(scene.getInputcon());
	    				item.setOutputcon(scene.getOutputcon());
	    				item.setAllowask(scene.isAllowask());
	    				item.setReplaytype(scene.getReplaytype());
	    				item.setSceneid(scene.getId());
	    				item.setItemtype(UKDataContext.AiItemType.USERINPUT.toString());
	    				userInputItems.add(item) ;
    				}
    			}
    			sceneItemRes.save(userInputItems) ;
    		}else {
    			SceneItem item = new SceneItem();
				item.setContent("");
				item.setOrgi(super.getOrgi(request));
				item.setCreater(super.getUser(request).getId());
				item.setInx(0);
				item.setInputcon(scene.getInputcon());
				item.setSceneid(scene.getId());
				item.setItemtype(UKDataContext.AiItemType.USERINPUT.toString());
				sceneItemRes.save(item) ;
    		}
    		
    		if(aireply!=null && aireply.length >0){
    			List<SceneItem> aiReplyItems = new ArrayList<SceneItem>();
    			for(int i=0 ; i<aireply.length ; i++){
    				String air = aireply[i] ;
    				if(!StringUtils.isBlank(air)){
	    				SceneItem item = new SceneItem();
	    				item.setContent(air);
	    				item.setOrgi(super.getOrgi(request));
	    				item.setCreater(super.getUser(request).getId());
	    				
	    				item.setAllowask(scene.isAllowask());
	    				item.setReplaytype(scene.getReplaytype());
	    				
	    				item.setInputcon(scene.getInputcon());
	    				item.setOutputcon(scene.getOutputcon());
	    				
	    				item.setInx(i);
	    				item.setSceneid(scene.getId());
	    				item.setItemtype(UKDataContext.AiItemType.AIREPLY.toString());
	    				aiReplyItems.add(item) ;
    				}
    			}
    			sceneItemRes.save(aiReplyItems) ;
    			CacheHelper.getSystemCacheBean().put(scene.getId(), aiReplyItems, super.getOrgi(request)) ;
    			CacheHelper.getSystemCacheBean().put("scene."+scene.getId(), scene, super.getOrgi(request)) ;
    		}
    		
    		sceneRes.save(scene) ;
    		/**
    		 * 重新初始化 AI对话
    		 */
    		AiUtils.init(UKDataContext.SYSTEM_ORGI) ;
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/scene.html"+(!StringUtils.isBlank(type) ? "?type="+type : "")));
    }
    
    @RequestMapping("/scene/edit")
    @Menu(type = "xiaoe" , subtype = "sceneedit")
    public ModelAndView sceneedit(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String type) {
    	map.put("type", type);
    	map.put("inputConList", UKeFuDic.getInstance().getSysDic("com.dic.xiaoe.input"));
    	map.put("outputConList", UKeFuDic.getInstance().getSysDic("com.dic.xiaoe.output"));
    	
    	map.put("scene", sceneRes.findByIdAndOrgi(id,super.getOrgi(request))) ;
    	map.put("sceneItemList", sceneItemRes.findByOrgiAndSceneid(super.getOrgi(request), id)) ;
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/scene/edit"));
    }
    
    @RequestMapping("/scene/update")
    @Menu(type = "xiaoe" , subtype = "sceneupdate")
    public ModelAndView sceneupdate(HttpServletRequest request ,@Valid Scene scene , @Valid String[] userinput, @Valid String[] aireply , @Valid String type) throws IOException {
    	if(!StringUtils.isBlank(scene.getTitle())){
    		Scene temp = sceneRes.findByIdAndOrgi(scene.getId(),super.getOrgi(request)) ;
    		if(!StringUtils.isBlank(type)){
    			scene.setCate(type);
    		}else{
    			scene.setCate(UKDataContext.DEFAULT_TYPE);
    		}
    		if(userinput!=null && userinput.length >0){
    			scene.setUserinput(userinput[0]);
    		}
    		if(aireply!=null && aireply.length >0){
    			scene.setAireply(aireply[0]);
    		}
    		scene.setCreater(temp.getCreater());
    		scene.setCreatetime(temp.getCreatetime());
    		scene.setOrgi(super.getOrgi(request));
    		
    		sceneItemRes.delete(sceneItemRes.findByOrgiAndSceneid(super.getOrgi(request), scene.getId()));
    		
    		if(userinput!=null && userinput.length >0){
    			List<SceneItem> userInputItems = new ArrayList<SceneItem>();
    			for(int i=0 ; i<userinput.length ; i++){
    				String user = userinput[i] ;
    				SceneItem item = new SceneItem();
    				item.setContent(user);
    				item.setOrgi(super.getOrgi(request));
    				item.setCreater(super.getUser(request).getId());
    				item.setInx(i);
    				item.setInputcon(scene.getInputcon());
    				item.setSceneid(scene.getId());
    				item.setItemtype(UKDataContext.AiItemType.USERINPUT.toString());
    				userInputItems.add(item) ;
    			}
    			sceneItemRes.save(userInputItems) ;
    		}else {
    			SceneItem item = new SceneItem();
				item.setContent("");
				item.setOrgi(super.getOrgi(request));
				item.setCreater(super.getUser(request).getId());
				item.setInx(0);
				item.setInputcon(scene.getInputcon());
				item.setSceneid(scene.getId());
				item.setItemtype(UKDataContext.AiItemType.USERINPUT.toString());
				sceneItemRes.save(item) ;
    		}
    		
    		if(aireply!=null && aireply.length >0){
    			List<SceneItem> aiReplyItems = new ArrayList<SceneItem>();
    			for(int i=0 ; i<aireply.length ; i++){
    				String air = aireply[i] ;
    				SceneItem item = new SceneItem();
    				item.setContent(air);
    				item.setOrgi(super.getOrgi(request));
    				item.setCreater(super.getUser(request).getId());
    				item.setInx(i);
    				item.setOutputcon(scene.getOutputcon());
    				item.setSceneid(scene.getId());
    				item.setItemtype(UKDataContext.AiItemType.AIREPLY.toString());
    				aiReplyItems.add(item) ;
    			}
    			sceneItemRes.save(aiReplyItems) ;
    			CacheHelper.getSystemCacheBean().put(scene.getId(), aiReplyItems, super.getOrgi(request)) ;
    			CacheHelper.getSystemCacheBean().put("scene."+scene.getId(), scene, super.getOrgi(request)) ;
    		}
    		
    		sceneRes.save(scene) ;
    		
    		/**
    		 * 重新初始化 AI对话
    		 */
    		AiUtils.init(UKDataContext.SYSTEM_ORGI) ;
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/scene.html"+(!StringUtils.isBlank(type) ? "?type="+type : "")));
    }
    
    
    @RequestMapping("/scene/delete")
    @Menu(type = "xiaoe" , subtype = "scenedelete")
    public ModelAndView scenedelete(HttpServletRequest request ,@Valid String id , @Valid String type) throws IOException {
    	if(!StringUtils.isBlank(id)){
    		sceneRes.delete(id);
    		sceneItemRes.delete(sceneItemRes.findByOrgiAndSceneid(super.getOrgi(request), id));
    		/**
    		 * 重新初始化 AI对话
    		 */
    		AiUtils.init(UKDataContext.SYSTEM_ORGI) ;
    		if(CacheHelper.getSystemCacheBean().getCacheObject(id, super.getOrgi(request)) != null){
				CacheHelper.getSystemCacheBean().delete(id,super.getOrgi(request)) ; 
			}
    		if(CacheHelper.getSystemCacheBean().getCacheObject("scene"+id, super.getOrgi(request)) != null){
				CacheHelper.getSystemCacheBean().delete("scene"+id,super.getOrgi(request)) ; 
			}
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/scene.html"+(!StringUtils.isBlank(type) ? "?type="+type : "")));
    }
    
    @RequestMapping("/scene/type/add")
    @Menu(type = "xiaoe" , subtype = "scenetypeadd")
    public ModelAndView scenetypeadd(ModelMap map , HttpServletRequest request ) {
    	map.addAttribute("areaList", areaRepository.findByOrgi(super.getOrgi(request))) ;
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/scene/addtype"));
    }
    
    @RequestMapping("/scene/type/save")
    @Menu(type = "xiaoe" , subtype = "scenetypesave")
    public ModelAndView scenetypesave(HttpServletRequest request ,@Valid SceneType type) {
    	int tempTypeCount = sceneTypeRes.countByNameAndOrgi(type.getName(), super.getOrgi(request)) ;
    	if(tempTypeCount == 0){
    		type.setOrgi(super.getOrgi(request));
    		type.setCreatetime(new Date());
    		type.setUpdatetime(new Date());
    		type.setCreater(super.getUser(request).getId());
    		sceneTypeRes.save(type) ;
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/scene.html"));
    }
    
    @RequestMapping("/scene/type/edit")
    @Menu(type = "xiaoe" , subtype = "scenetypeedit")
    public ModelAndView scenetypeedit(ModelMap map , HttpServletRequest request, @Valid String type ) {
    	map.put("sceneType", sceneTypeRes.findByIdAndOrgi(type,super.getOrgi(request))) ;
    	map.addAttribute("areaList", areaRepository.findByOrgi(super.getOrgi(request))) ;
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/scene/edittype"));
    }
    
    @RequestMapping("/scene/type/update")
    @Menu(type = "xiaoe" , subtype = "scenetypeupdate")
    public ModelAndView scenetypeupdate(HttpServletRequest request ,@Valid SceneType type) {
    	int tempTypeCount = sceneTypeRes.countByNameAndOrgi(type.getName(), super.getOrgi(request)) ;
    	if(tempTypeCount == 0){
    		SceneType temp = sceneTypeRes.findByIdAndOrgi(type.getId(), super.getOrgi(request)) ;
    		temp.setName(type.getName());
    		sceneTypeRes.save(temp) ;
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/scene.html?type="+type.getId()));
    }
    
    @RequestMapping("/scene/type/delete")
    @Menu(type = "xiaoe" , subtype = "scenedelete")
    public ModelAndView scenetypedelete(HttpServletRequest request ,@Valid String id , @Valid String type) {
    	Page<Topic> page = topicRes.getTopicByCateAndOrgi(type,super.getOrgi(request), null, super.getP(request), super.getPs(request)) ;
    	String msg = null ;
    	if(page.getTotalElements() == 0){
	    	if(!StringUtils.isBlank(id)){
	    		sceneTypeRes.delete(id);
	    	}
    	}else{
    		msg = "notempty" ;
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/scene.html"+(msg!=null ? "?msg=notempty" : "")));
    }
    @RequestMapping("/topicshot")
    @Menu(type = "xiaoe" , subtype = "scenetypeedit")
    public ModelAndView topicshot(ModelMap map , HttpServletRequest request, @Valid String type , @Valid String aiid ) {
    	map.addAttribute("aiid", aiid);
    	SearchRequestBuilder searchRequestBuilder = UKDataContext.getTemplet().getClient().prepareSearch(UKDataContext.SYSTEM_INDEX).setTypes(UKDataContext.EsTable.UK_USEREVENT.toString());
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
		
		searchRequestBuilder = UKDataContext.getTemplet().getClient().prepareSearch(UKDataContext.SYSTEM_INDEX).setTypes(UKDataContext.EsTable.UK_CHAT_MESSAGE.toString());
		boolQueryBuilder = new BoolQueryBuilder();
		boolQueryBuilder.must(termQuery("orgi" , super.getOrgi(request))) ;
		boolQueryBuilder.must(termQuery("aiid" , aiid)) ;
		boolQueryBuilder.must(termQuery("chatype" , "aireply")) ;
		searchRequestBuilder.setQuery(boolQueryBuilder);
		searchRequestBuilder.setSize(0).setFrom(0);
		AggregationBuilder<?> builder =  AggregationBuilders.terms("topicid").field("topicid").size((super.getP(request)+1)*10);
		builder.subAggregation(AggregationBuilders.terms("topicid").field("topicid"));
		searchRequestBuilder.addAggregation(AggregationBuilders.cardinality("topicnum").field("topicid"));
		searchRequestBuilder.addAggregation(builder);
		ArrayList<Topic> topicList = new ArrayList<Topic>();
		SearchDataBean searchDataBean = SearchTools.findAllPageAggResultChatMessage(searchRequestBuilder,new PageRequest(super.getP(request), super.getPs(request)), UKDataContext.EsTable.UK_CHAT_MESSAGE.toString());
		if(searchDataBean != null && searchDataBean.getList().size() > 0) {
			for(Topic topic : this.topicRes.findByIdInAndOrgi(searchDataBean.getList(),super.getOrgi(request))) {
				topicList.add(topic);
			}
			map.addAttribute("topicsList",new PageImpl<Topic>(topicList ,new PageRequest(super.getP(request), 10),searchDataBean.getSize()));
		}
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/topicshot"));
    }
    
    
    @RequestMapping("/chat/match")
    @Menu(type = "xiaoe" , subtype = "knowledgematch")
    public ModelAndView match(ModelMap map , HttpServletRequest request ,@Valid String id) {
		map.put("chatMessage" , chatMessageRes.findByIdAndOrgi(id,super.getOrgi(request)));
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/chat/match"));
    }
}